#include "editroledlg.h"
#include "ui_editroledlg.h"

#include <QPixmap>
#include <QTreeWidget>
#include <algorithm>

EditRoleDlg::EditRoleDlg(QString id,QList<DictData> dictList,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EditRoleDlg)
{
    ui->setupUi(this);
    this->id = id;
    this->dictList = dictList;
    if(id == "0"){
        setWindowTitle("添加角色");
    }else{
        setWindowTitle("修改角色");
    }
    QPixmap pix(":/image/res/what.jpg");
    pix.scaled(15,15);
    ui->btn_what->setIcon(pix);
    ui->btn_what->setToolTip("控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)");
    setWindowIcon(QPixmap(":/image/res/stm.jpg"));
    treeWidgetHeight = ui->treeWidget->height();

    init();
}

EditRoleDlg::~EditRoleDlg()
{
    delete ui;
}

void EditRoleDlg::init()
{
    ui->radioButton->setText(dictList[0].dictLabel);
    ui->radioButton->setChecked(1);
    ui->radioButton_2->setText(dictList[1].dictLabel);
    connect(ui->treeWidget,SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(treeItemChanged(QTreeWidgetItem*,int)));
    if(id != "0"){      //修改
        //角色数据
        QByteArray *bytes = roleManagerApi.getById(id);
        QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
        QJsonObject data = obj.value("data").toObject();
        role = new Role(Role::toRole(data));
        if(obj.value("code") != 200){
            return;
        }else{
            ui->lineEdit_roleName->setText(role->roleName);
            ui->lineEdit_roleKey->setText(role->roleKey);
            ui->spinBox->setValue(role->roleSort);
            role->status == "0" ? ui->radioButton->setChecked(1) : ui->radioButton_2->setChecked(1);
            ui->checkBox_fatherAndSon->setChecked(role->menuCheckStrictly == 1 ? 1 : 0);
            ui->textEdit->setPlainText(role->remark);
        }
        //权限数据
        QByteArray *bytes1 = roleManagerApi.getMenuById(id);
        QJsonObject obj1 = QJsonDocument::fromJson(*bytes1).object();

        if(obj1.value("code") != 200){
            return;
        }else{
            //树
            QJsonArray menusIds = obj1.value("menus").toArray();
            for(int i = 0;i< menusIds.size();i++){
                QJsonObject o = menusIds.at(i).toObject();
                QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget,QStringList(o.value("label").toString()));
                item->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsSelectable);
                item->setCheckState(0,Qt::Unchecked);
                item->setData(1,0,o.value("id"));
                setTreeWidget(o.value("children").toArray(),item);
            }

            //检测所属权限
            QJsonArray ownMenusIds = obj1.value("checkedKeys").toArray();
            QList<int> ownIds;
            for(int i = 0;i< ownMenusIds.size();i++){
                ownIds.append(ownMenusIds.at(i).toInt());
            }
            std::reverse(ownIds.begin(),ownIds.end());
            for(int i = 0;i< ownMenusIds.size();i++){
                int id = ownMenusIds.at(i).toInt();
                for (int j = 0; j < ui->treeWidget->topLevelItemCount(); ++j) {
                    QTreeWidgetItem *item = ui->treeWidget->topLevelItem(j);
                    if(item->data(1,0).toInt() == id){
                        item->setCheckState(0,Qt::Checked);
                        utils.selectAllSonNode(item);
                    }else{
                        for (int k = 0; k < item->childCount(); ++k) {
                            QTreeWidgetItem *childItem = item->child(k);
                            utils.setOwnMenu(id,childItem);
                        }
                    }

                }
            }
        }
    }else{
        treeSelect();
    }

}

void EditRoleDlg::treeSelect()
{
    QByteArray *data = roleManagerApi.treeSelect();
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    arrTree = obj.value("data").toArray();
    for(int i = 0;i< arrTree.size();i++){
        QJsonObject o = arrTree.at(i).toObject();
        QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget,QStringList(o.value("label").toString()));
        item->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsSelectable);
        item->setCheckState(0,Qt::Unchecked);
        item->setData(1,0,o.value("id"));
        setTreeWidget(o.value("children").toArray(),item);
    }
}

void EditRoleDlg::setTreeWidget(QJsonArray arr,QTreeWidgetItem *parent)
{
    for(int i = 0;i< arr.size();i++){
        QJsonObject o = arr.at(i).toObject();
        QTreeWidgetItem *item = new QTreeWidgetItem(parent,QStringList(o.value("label").toString()));
        item->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsSelectable);
        item->setCheckState(0,Qt::Unchecked);
        item->setData(1,0,o.value("id"));
        setTreeWidget(o.value("children").toArray(),item);
    }
}

void EditRoleDlg::treeItemChanged(QTreeWidgetItem *item, int column)
{
    if(Qt::Checked == item->checkState(0)){
        int count = item->childCount();
        if(count > 0){
            for(int i = 0;i< count;i++){
                item->child(i)->setCheckState(0,Qt::Checked);
            }
        }else{
            utils.updateParentItem(item);
        }
    }else if(Qt::Unchecked == item->checkState(0)){
        int count = item->childCount();
        if(count > 0){
            for(int i = 0;i< count;i++){
                item->child(i)->setCheckState(0,Qt::Unchecked);
            }
        }else{
            utils.updateParentItem(item);
        }
    }
    ui->treeWidget->height();
}

void EditRoleDlg::on_btn_cancel_clicked()
{
    this->close();
}

void EditRoleDlg::on_treeWidget_itemExpanded(QTreeWidgetItem *item)
{
    int count = item->childCount();
    for(int i = 0;i< count;i++){
        QTreeWidgetItem *child = item->child(i);
        treeWidgetHeight += ui->treeWidget->visualItemRect(child).height();
        if(child->isExpanded()){
            on_treeWidget_itemExpanded(child);
        }
    }
    if(treeWidgetHeight > 350){
        ui->treeWidget->setFixedHeight(350);
    }else{
        ui->treeWidget->setFixedHeight(treeWidgetHeight);
    }
}

void EditRoleDlg::on_treeWidget_itemCollapsed(QTreeWidgetItem *item)
{
    int rowHeight = ui->treeWidget->visualItemRect(item).height();
    int minHeight = rowHeight * ui->treeWidget->topLevelItemCount();
    int count = item->childCount();
    treeWidgetHeight -= rowHeight * count;
    for(int i = 0;i< count;i++){
        if(item->child(i)->isExpanded()){
            on_treeWidget_itemCollapsed(item->child(i));
        }
    }
    if(treeWidgetHeight > 350){
        ui->treeWidget->setFixedHeight(350);
    }else if(treeWidgetHeight < 80){
        treeWidgetHeight = 80;
        ui->treeWidget->setFixedHeight(minHeight);
    }else{
        ui->treeWidget->setFixedHeight(treeWidgetHeight);
    }
    adjustSize();
}

void EditRoleDlg::on_checkBox_expand_clicked()
{
    if(ui->checkBox_expand->isChecked()){
        treeWidgetHeight = 1714;
        ui->treeWidget->setMaximumHeight(350);
        ui->treeWidget->expandAll();
    }else{
        ui->treeWidget->collapseAll();
    }
}

void EditRoleDlg::on_checkBox_selectAll_clicked()
{
    int count = ui->treeWidget->topLevelItemCount();
    if(ui->checkBox_selectAll->isChecked()){
        for(int i = 0;i< count;i++){
            QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i);
            utils.selectAll(item);
        }
    }else{
        for(int i = 0;i< count;i++){
            QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i);
            utils.unSelectAll(item);
        }
    }
}

void EditRoleDlg::on_checkBox_fatherAndSon_clicked()
{
    fatherAndSonLink = ui->checkBox_fatherAndSon->isChecked();
    if(fatherAndSonLink){
        connect(ui->treeWidget,SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(treeItemChanged(QTreeWidgetItem*,int)));
    }else{
        disconnect(ui->treeWidget,SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(treeItemChanged(QTreeWidgetItem*,int)));
    }
}

void EditRoleDlg::on_btn_ok_clicked()
{
    menuIds.clear();
    if(id == "0"){  //新增
        role = new Role;
    }
    if(ui->lineEdit_roleName->text().isEmpty()){
        ui->lineEdit_roleName->setPlaceholderText("角色名称不能为空");
        ui->lineEdit_roleName->setStyleSheet("border:1px solid red;");
        return;
    }else{
        ui->lineEdit_roleName->setPlaceholderText("");
        ui->lineEdit_roleName->setStyleSheet("");
        role->roleName = ui->lineEdit_roleName->text();
    }
    if(ui->lineEdit_roleKey->text().isEmpty()){
        ui->lineEdit_roleKey->setPlaceholderText("权限字符不能为空");
        ui->lineEdit_roleKey->setStyleSheet("border:1px solid red;");
        return;
    }else{
        ui->lineEdit_roleKey->setPlaceholderText("");
        ui->lineEdit_roleKey->setStyleSheet("");
        role->roleKey = ui->lineEdit_roleKey->text();
    }
    role->roleSort = ui->spinBox->text().toInt();
    role->status = ui->radioButton->isChecked() ? "0" : "1";
    //权限
    for(int i = 0;i< ui->treeWidget->topLevelItemCount();i++){
        QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i);
        if(item->checkState(0) == Qt::Checked){
            menuIds.append(item->data(1,0).toInt());
        }
        utils.getMenuIds(item,&menuIds);
    }
    role->menuIds = menuIds;
    role->remark = ui->textEdit->toPlainText();
    role->menuCheckStrictly = fatherAndSonLink;
    role->deptCheckStrictly = 1;
    if(id == "0"){  //新增
        QByteArray *res = roleManagerApi.addRole(role);
        QJsonObject data = QJsonDocument::fromJson(*res).object();
        if(data.value("code").toInt() == 200){
            QMessageBox::warning(0,"提示",data.value("msg").toString());
            this->close();
            emit success();
        }
    }else{
        QByteArray *res = roleManagerApi.updateRole(role);
        QJsonObject data = QJsonDocument::fromJson(*res).object();
        if(data.value("code").toInt() == 200){
            QMessageBox::warning(0,"提示",data.value("msg").toString());
            this->close();
            emit success();
        }
    }
}

